import { BaseState } from './BaseState';
import { Vec3 } from 'cc';

/**
 * AI游荡状态
 * 
 * 功能：
 * 1. 控制AI的随机移动
 * 2. 处理游荡范围限制
 * 3. 管理游荡行为模式
 * 4. 处理环境交互
 * 
 * 特点：
 * 1. 可配置的游荡参数
 * 2. 智能路径选择
 * 3. 避障系统
 * 4. 区域限制
 */
export class WanderState extends BaseState {
    private wanderRadius: number = 10;
    private targetPosition: Vec3 | null = null;
    private wanderTimer: number = 0;
    private wanderDuration: number = 5;

    public enter(): void {
        this.setNewWanderTarget();
    }

    public exit(): void {
        this.controller.stopMoving();
        this.targetPosition = null;
        this.wanderTimer = 0;
    }

    public update(dt: number): void {
        this.wanderTimer += dt;

        // 检测威胁和食物
        if (this.controller.detectThreat()) {
            this.controller.changeState('flee');
            return;
        }

        if (this.controller.detectFood()) {
            this.controller.changeState('chase');
            return;
        }

        // 到达目标点或超时，返回闲置状态
        if (this.hasReachedTarget() || this.wanderTimer >= this.wanderDuration) {
            this.controller.changeState('idle');
            return;
        }

        // 移动向目标点
        if (this.targetPosition) {
            this.controller.moveTowards(this.targetPosition);
        }
    }

    private setNewWanderTarget(): void {
        const currentPos = this.controller.getPosition();
        const randomOffset = this.getRandomPosition(this.wanderRadius);
        this.targetPosition = new Vec3(
            currentPos.x + randomOffset.x,
            currentPos.y,
            currentPos.z + randomOffset.z
        );
    }

    private hasReachedTarget(): boolean {
        if (!this.targetPosition) return true;
        
        const currentPos = this.controller.getPosition();
        const distance = Vec3.distance(currentPos, this.targetPosition);
        return distance < 0.5;
    }
} 